﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Forms.Depo;
using ConfExpert.Utility.Peripheral;
using DevExpress.XtraEditors;
using DevTeam;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace ConfExpert.Forms
{
    public partial class KartelaTarama : XForm
    {
        class PanelEx : PanelControl
        {
            public PanelEx()
            {
                DoubleBuffered = true;
                this.SetStyle(ControlStyles.ResizeRedraw, true);
            }
        }

        public KartelaTarama()
        {
            InitializeComponent();
        }

        int Tip
        {
            get
            {
                return radioGroup1.SelectedIndex;   //0. Kumaş, 1. Kod
            }
        }

        float kucultme = 0.15f;
        private void KartelaTarama_Load(object sender, EventArgs e)
        {



            btnGo.Click += btn_Click;

            panelEx1.AutoScroll = true;
            //panelEx1.MouseMove += new MouseEventHandler(panelEx1_MouseMove);
            panelEx1.MouseUp += new MouseEventHandler(panelEx1_MouseUp);
            panelEx1.MouseDown += new MouseEventHandler(panelEx1_MouseDown);
            //panelEx1.Properties.ShowZoomSubMenu = DevExpress.Utils.DefaultBoolean.True;
            panelEx1.PreviewKeyDown += panelEx1_PreviewKeyDown;

            Pen1 = new Pen(Color.Black, 1);
            Pen1.DashStyle = DashStyle.Solid;

            Pen2 = new Pen(Color.Red, 1);
            Pen2.DashStyle = DashStyle.Solid;

            colorPickEdit1.ColorChanged += colorPickEdit1_ColorChanged;
            colorPickEdit1.Color = Pen1.Color;

            colorPickEdit2.ColorChanged += colorPickEdit2_ColorChanged;
            colorPickEdit2.Color = Pen2.Color;

            calcEdit1.Value = calcEdit2.Value = 0;
            calcEdit3.Value = 2;
            calcEdit4.Value = 2;

            calcEdit1.ValueChanged += calcEdit1_ValueChanged;
            calcEdit2.ValueChanged += calcEdit1_ValueChanged;
            calcEdit3.ValueChanged += calcEdit1_ValueChanged;
            calcEdit4.ValueChanged += calcEdit1_ValueChanged;
            calcEdit1_ValueChanged(null, null);

            this.panelEx1.Paint += panelEx1_Paint;
            this.panelEx1.MouseWheel += panelEx1_MouseWheel;
            btnScan.Click += btnScan_Click;

            beKatalog.EditValue = 2;
            beKatalog.ButtonClick += buttonEdit1_ButtonClick;
            //ds.KatalogLinesPart.AddAutoIncrementalColumn("KatalogLinesPartId");
            //ds.KatalogLinesPart.SetPK("KatalogLinesPartId");
            beKatalog.Properties.ReadOnly = true;

            beKatalogLines.Enabled = true;
            //beKatalogLines.Visible = labelControl6.Visible =AmI(17);
            beKatalogLines.ButtonClick += beKatalogLines_ButtonClick;
            beKatalogLines.Properties.ReadOnly = true;

            btnThumb.Visible = ytk(117);
            btnThumb.Click += btnThumb_Click;
            panelEx1.Cursor = Cursors.Cross;

            lblZoom.Text = "x" + enlargement;
        }

        void btnThumb_Click(object sender, EventArgs e)
        {
            int KatalogId = beKatalog.EditValue.ToInt();
            DataTable dt = ExecuteDataTable("GetKatalogSayfalar", KatalogId);
            foreach (DataRow dr in dt.Rows)
            {
                bmOrg = ConvertByteArrayToImage(dr["BLOB"] as byte[]) as Bitmap;

                //if (dr["KatalogLinesId"].ToInt() > 53)
                //    bmOrg.RotateFlip(RotateFlipType.Rotate180FlipNone); //sil

                dr["BLOB"] = ConvertImageToByteArray(bmOrg, ImageFormat.Jpeg);     //null;
                dr["BLOBmini"] = ConvertImageToByteArray((Bitmap)bmOrg.Resize(kucultme), ImageFormat.Jpeg);

                GC.Collect();
            }
            ExecuteNonQuery("UpdKatalogThumb", dt);
        }

        void panelEx1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.Control)
                switch (e.KeyCode)
                {
                    case Keys.D0: Sil(); break;
                    case Keys.Right: Saga(); break;
                    case Keys.Left: Sola(); break;
                }
        }

        private void Sola()
        {
            int KatalogLinesId = beKatalogLines.Text.ToInt();
            if (KatalogLinesId > 0)
            {
                MyData.KatalogLinesRow r = ds.KatalogLines.NewKatalogLinesRow();
                r.KatalogLinesId = KatalogLinesId;
                Image i2 = bmOrg;
                i2.RotateFlip(RotateFlipType.Rotate270FlipNone);
                r.BLOB = ConvertImageToByteArray(i2, ImageFormat.Jpeg);
                ds.KatalogLines.AddKatalogLinesRow(r);

                ExecuteNonQuery("UpdKatalogLines", ds.KatalogLines);

                panelEx1.Invalidate();
                ds.KatalogLines.Clear();
            }
        }

        private void Saga()
        {
            {
                int KatalogLinesId = beKatalogLines.Text.ToInt();
                if (KatalogLinesId > 0)
                {
                    MyData.KatalogLinesRow r = ds.KatalogLines.NewKatalogLinesRow();
                    r.KatalogLinesId = KatalogLinesId;
                    Image i2 = bmOrg;
                    i2.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    r.BLOB = ConvertImageToByteArray(i2, ImageFormat.Jpeg);
                    ds.KatalogLines.AddKatalogLinesRow(r);

                    ExecuteNonQuery("UpdKatalogLines", ds.KatalogLines);

                    panelEx1.Invalidate();
                    ds.KatalogLines.Clear();
                }
            }
        }

        private void Sil()
        {
            int KatalogLinesId = beKatalogLines.Text.ToInt();
            if (KatalogLinesId > 0)
                if (XtraMessageBox.Show("Silmek istediğinize Emin misiniz?", "Teyid", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    ExecuteNonQuery("DelKatalogLines", KatalogLinesId);
                    Notify("silindi.");
                }

        }

        //void ExecQueryTV(string SP, params object[] p)
        //{
        //    using (SqlConnection sqlConn = new SqlConnection(Session.DataManager.ConnectionString))
        //    {
        //        sqlConn.Open();
        //        SqlCommand sqlCmd = sqlConn.CreateCommand();
        //        sqlCmd.CommandText = SP;
        //        sqlCmd.CommandType = CommandType.StoredProcedure;
        //        SqlParameter[] parameters = new SqlParameter[2];
        //        parameters[0] = new SqlParameter("@tbl1", SqlDbType.Structured);
        //        parameters[0].Value = p[0];
        //        parameters[1] = new SqlParameter("@tbl2", SqlDbType.Structured);
        //        parameters[1].Value = p[1];
        //        sqlCmd.Parameters.AddRange(parameters);
        //        sqlCmd.ExecuteNonQuery();
        //    }
        //}

        //void ExecQueryTV2(string SP, params object[] p)
        //{
        //    using (SqlConnection sqlConn = new SqlConnection(Session.DataManager.ConnectionString))
        //    {
        //        sqlConn.Open();
        //        SqlCommand sqlCmd = sqlConn.CreateCommand();
        //        sqlCmd.CommandText = SP;
        //        sqlCmd.CommandType = CommandType.StoredProcedure;
        //        SqlParameter[] parameters = new SqlParameter[1];
        //        parameters[0] = new SqlParameter("@tbl", SqlDbType.Structured);
        //        parameters[0].Value = p[0];
        //        sqlCmd.Parameters.AddRange(parameters);
        //        sqlCmd.ExecuteNonQuery();
        //    }
        //}



        void beKatalogLines_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            int KatalogId = beKatalog.EditValue.ToInt();
            int KatalogLinesId = beKatalogLines.EditValue.ToInt();
            using (KatalogLinesSec ksec = new KatalogLinesSec(KatalogId, KatalogLinesId))
            {
                if (ksec.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    beKatalogLines.EditValue = ksec.KatalogLinesId;

                    DataTable dt = ExecuteDataTable("GetKatalogLinesId", beKatalogLines.EditValue.ToInt());
                    if (dt.Rows.Count > 0)
                    {
                        DataRow dr = dt.Rows[0];
                        //beKatalogLines.EditValue = dr["KatalogLinesId"].ToInt();
                        txtSayfaNotu.Text = dr["SayfaNo"].ToString();
                        bmOrg = ConvertByteArrayToImage(dr["BLOB"] as byte[]) as Bitmap;

                        panelEx1.Invalidate();
                    }
                }
            }
        }

        void buttonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            using (KartelaSec ks = new KartelaSec())
                if (ks.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    beKatalog.EditValue = ks.KatalogId;
                    btnScan.Enabled = true;
                }
        }

        //void cmbSeciliAlan_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    panelEx1.Cursor = (cmbSeciliAlan.Text.Contains("aydır") ? Cursors.Hand : Cursors.Cross);
        //}

        void btnScan_Click(object sender, EventArgs e)
        {
            Image scanned;

            scanned = Scanner.Scan600(25);

            if (scanned != null)
            {
                GC.Collect();
                bmOrg = new Bitmap(scanned);
                bmOrgMini = (Bitmap)bmOrg.Resize(kucultme);
                panelEx1.Size = bmOrg.Size;
                panelEx1.Invalidate();
            }
        }


        public double enlargement = 0.28;   //1.0;
        void panelEx1_MouseWheel(object sender, MouseEventArgs e)
        {
            if (enlargement + e.Delta / 1000.0 <= 1.0 &&
                enlargement + e.Delta / 1000.0 > 0.1)
            {
                enlargement += e.Delta / 1000.0;
                lblZoom.Text = "x" + enlargement;

                panelEx1.Invalidate();
            }
        }

        double x1 = 0, x1Org = 0,
            x2 = 0, x2Org = 0,
            y1 = 0, y1Org = 0,
            y2 = 0, y2Org = 0;
        Bitmap bm, bmOrg, bmOrgMini;

        int columns, rows, spaceW, spaceH;
        Pen Pen1, Pen2;
        Point pnt;

        void panelEx1_Paint(object sender, PaintEventArgs e)
        {
            base.OnPaint(e);

            if (bmOrg != null)
            {
                Graphics g = e.Graphics;
                //g.ScaleTransform(enlargement, enlargement);

                bm = (Bitmap)bmOrg.Resize(enlargement);
                r1 = Buyut(r1Org, enlargement);
                r2 = Buyut(r2Org, enlargement);
                x1 = x1Org * enlargement;
                y1 = y1Org * enlargement;
                x2 = x2Org * enlargement;
                y2 = y2Org * enlargement;

                g.DrawImage(bm, new Rectangle(0, 0, bm.Width, bm.Height));

                for (int i = 0; i < columns; i++)
                    for (int j = 0; j < rows; j++)
                    {
                        int Rx = -(int)x1 + r1.X + i * (r1.Width + (int)(spaceW * enlargement));
                        int Ry = -(int)y1 + r1.Y + j * (r1.Height + (int)(spaceH * enlargement));

                        g.DrawRectangle(Pen1, Rx, Ry, r1.Width, r1.Height);

                        g.DrawRectangle(Pen2, -(int)x2 + r2.X + i * (r1.Width + (int)(spaceW * enlargement)),
                            -(int)y2 + r2.Y + j * (r1.Height + (int)(spaceH * enlargement)), r2.Width, r2.Height);
                    }
            }
        }

        Rectangle r1, r2, r1Org, r2Org;
        void Slice()
        {
            ds.KatalogLinesPart.Clear();
            int KatalogLinesId = beKatalogLines.EditValue.ToInt();
            for (int i = 0; i < columns; i++)
                for (int j = 0; j < rows; j++)
                {
                    Rectangle kesit = new Rectangle(-(int)x1Org + r1Org.X + i * (r1Org.Width + spaceW),
                        -(int)y1Org + r1Org.Y + j * (r1Org.Height + spaceH), r1Org.Width, r1Org.Height);

                    Rectangle kesit2 = new Rectangle(-(int)x2Org + r2Org.X + i * (r1Org.Width + spaceW),
                        -(int)y2Org + r2Org.Y + j * (r1Org.Height + spaceH), r2Org.Width, r2Org.Height);

                    if (kesit.Height > 0)
                    {
                        MyData.KatalogLinesPartRow rx = ds.KatalogLinesPart.NewKatalogLinesPartRow();
                        rx.BLOB = bmOrg.Crop(kesit).ToJPEG();
                        rx.KatalogLinesId = KatalogLinesId;
                        if (kesit2.Height > 0)
                            rx.BLOBKod = bmOrg.Crop(kesit2).ToJPEG();
                        ds.KatalogLinesPart.AddKatalogLinesPartRow(rx);
                    }
                }

            bool PageUpload = beKatalogLines.EditValue.ToInt() == 0;

            MyData.KatalogLinesRow rl = ds.KatalogLines.NewKatalogLinesRow();
            rl.KatalogId = beKatalog.EditValue.ToInt();
            rl.SayfaNo = txtSayfaNotu.Text;

            if (PageUpload)
                if (bmOrg != null)
                {
                    rl.BLOB = bmOrg.ToJPEG();
                    rl.BLOBmini = bmOrgMini.ToJPEG();
                }

            ds.KatalogLines.AddKatalogLinesRow(rl);

            ExecuteNonQuery("InsKatalogPhotos", ds.KatalogLines, ds.KatalogLinesPart);

            ds.KatalogLinesPart.Clear();
            ds.KatalogLines.Clear();
            GC.Collect();

            //if (!PageUpload)
            //beKatalogLines.PerformClick(beKatalogLines.Properties.Buttons[0]);
        }

        void calcEdit1_ValueChanged(object sender, System.EventArgs e)
        {
            spaceW = Convert.ToInt32(calcEdit1.Value);
            spaceH = Convert.ToInt32(calcEdit2.Value);
            columns = Convert.ToInt32(calcEdit3.Value);
            rows = Convert.ToInt32(calcEdit4.Value);

            panelEx1.Invalidate();
        }

        void colorPickEdit1_ColorChanged(object sender, EventArgs e)
        {
            Pen1.Color = colorPickEdit1.Color;
        }

        void colorPickEdit2_ColorChanged(object sender, EventArgs e)
        {
            Pen2.Color = colorPickEdit2.Color;
        }

        private void panelEx1_MouseMove(object sender, MouseEventArgs e)
        {
        }

        private void panelEx1_MouseDown(object sender, MouseEventArgs e)
        {
            //panelEx1.Focus();

            yon = (e.Button == MouseButtons.Left ? "l" : "r");
            panelEx1.Cursor = (yon == "r" ? Cursors.Hand : Cursors.Cross);
            pnt = new Point(e.Location.X, e.Location.Y);
        }

        string yon = string.Empty;
        private void panelEx1_MouseUp(object sender, MouseEventArgs e)
        {
            yon = (e.Button == MouseButtons.Left ? "l" : "r");
            panelEx1.Cursor = (yon == "r" ? Cursors.Hand : Cursors.Cross);

            Rectangle r = Buyut(GetRectangle(pnt, e.Location), 1.0 / enlargement);
            int rWidth = (int)((pnt.X - e.Location.X) / enlargement);
            int rHeight = (int)((pnt.Y - e.Location.Y) / enlargement);

            switch (Tip)
            {
                case 0:
                    switch (yon)
                    {
                        case "l":
                            r1Org = r;
                            break;

                        case "r":
                            x1Org += rWidth;
                            y1Org += rHeight;
                            break;
                    }
                    break;

                case 1:
                    switch (yon)
                    {
                        case "l":
                            r2Org = r;
                            break;

                        case "r":
                            x2Org += rWidth;
                            y2Org += rHeight;
                            break;
                    }
                    break;
            }

            panelEx1.Invalidate();
        }

        Rectangle Buyut(Rectangle r, double enlargement)
        {
            return new Rectangle(Convert.ToInt32(r.X * enlargement), Convert.ToInt32(r.Y * enlargement), Convert.ToInt32(r.Width * enlargement), Convert.ToInt32(r.Height * enlargement));
        }

        public Rectangle GetRectangle(Point p1, Point p2)
        {
            int top = Math.Min(p1.Y, p2.Y);
            int bottom = Math.Max(p1.Y, p2.Y);
            int left = Math.Min(p1.X, p2.X);
            int right = Math.Max(p1.X, p2.X);

            return Rectangle.FromLTRB(left, top, right, bottom);
        }

        void btn_Click(object sender, EventArgs e)
        {
            Slice();
        }

        private void panelControl1_Paint(object sender, PaintEventArgs e)
        {

        }


    }
}
